#define _CRT_SECURE_NO_WARNINGS
#include "list.h"

ListNode* list_inite()
{
	ListNode *head = (ListNode*)malloc(sizeof(ListNode));
	if (head == NULL)
	{
		perror("INITIALIZATION");
		exit(-1);
	}
	head->next = head;
	head->prev = head;
	return head;
}

static ListNode* buy_list_node(ln_date_type x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

void list_push_back(ListNode* head, ln_date_type x)
{
	assert(head);
	ListNode* newnode = buy_list_node(x);
	ListNode* tail = head->prev;
	tail->next = newnode;
	head->prev = newnode;
	newnode->next = head;
	newnode->prev = tail;
	newnode->data = x;
}

void list_push_front(ListNode* head, ln_date_type x)
{
	assert(head);
	ListNode* newnode = buy_list_node(x);
	ListNode* front = head->next;
	head->next = newnode;
	front->prev = newnode;
	newnode->next = front;
	newnode->prev = head;
	newnode->data = x;
}

void list_print(ListNode* head)
{
	assert(head);
	ListNode* tail = head->next;
	while (tail != head)
	{
		printf("%d ", tail->data);
		tail = tail->next;
	}
	printf("\n");
}

void list_pop_back(ListNode* head)
{
	assert(head&&head!=head->next);
	ListNode* tail, * tmp;
	tail = head->prev;
	tmp = tail->prev;
	tmp->next = head;
	head->prev = tmp;
	free(tail);
	tail = NULL;
}

void list_pop_front(ListNode* head)
{
	assert(head&&head!=head->next);
	ListNode* front, * tmp;
	front = head->next;
	tmp = front->next;
	tmp->prev = head;
	head->next = tmp;
	free(front);
	front = NULL;
}

ListNode* list_find(ListNode* head, ln_date_type x)
{
	assert(head && head != head->next);
	ListNode* cur = head->next;
	while (cur != head)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}

void list_insert_back(ListNode* pos, ln_date_type x)
{
	assert(pos);
	ListNode* newnode = buy_list_node(x);
	ListNode* tmp = pos->next;
	pos->next = newnode;
	newnode->prev = pos;
	newnode->next = tmp;
	tmp->prev = newnode;
}

void list_insert_front(ListNode* pos, ln_date_type x)
{
	assert(pos);
	ListNode* newnode = buy_list_node(x);
	ListNode* tmp = pos->prev;
	tmp->next = newnode;
	newnode->prev = tmp;
	newnode->next = pos;
	pos->prev = newnode;
}

void list_erase(ListNode* head,ListNode* pos)
{
	assert(pos&&head&&pos!=head);
	ListNode* front, * back;
	front = pos->prev;
	back = pos->next;
	front->next = back;
	back->prev = front;
	free(pos);
	pos = NULL;
}

void list_destory(ListNode* head)
{
	assert(head);
	ListNode* cur = head->next;
	while (cur != head)
	{
		ListNode* tmp = cur->next;
		free(cur);
		cur = tmp;
	}
	free(head);
	head = NULL;
}